<template>
	<gui-page :fullPage="true">
		<template v-slot:gBody>
			<view class="login-container">
				<!-- 将表单内容放在底部 -->
				<view class="login-content">
					<view class="logo-container">
						<image src="@/static/login/logo.png" mode="widthFix" class="logo-image"></image>
					</view>

					<!-- 登录方式切换 -->
					<view class="login-type-switch">
						<text :class="{'active-tab': loginType === 'password'}"
							@click="switchLoginType('password')">账号登录</text>
						<text :class="{'active-tab': loginType === 'sms'}" @click="switchLoginType('sms')">验证码登录</text>
					</view>

					<form @submit="submit" class="login-form">
						<!-- 账号密码登录 -->
						<view v-if="loginType === 'password'">
							<view class="input-container">
								<input v-model="userName" type="text" class="form-input" name="username"
									placeholder="请输入用户名/手机号/厂牌号登录" />
								<view class="input-icon" v-if="userName.length >= 1">
									<text class="gui-icons" @click="clearUname">&#xe78a;</text>
								</view>
							</view>
							<view class="input-container">
								<input v-model="password" :type="showPassword?'password':'text'" class="form-input"
									name="password" placeholder="请输入密码" />
								<view class="input-icon">
									<text class="gui-icons"
										:class="[!showPassword ? 'gui-primary-color' : 'gui-color-gray']"
										v-if="password.length >= 1" @click="changePwdType">&#xe609;</text>
								</view>
							</view>
							<view class="form-options">
								<label>
									<radio :checked="save_password" @click="savePassword" /><text>记住密码</text>
								</label>

								<navigator url="/pages/login/reset">忘记密码</navigator>
							</view>
						</view>

						<!-- 短信验证码登录 -->
						<view v-else-if="loginType === 'sms'">
							<view class="input-container">
								<input v-model="phoneNumber" type="number" class="form-input" name="phoneNumber"
									placeholder="请输入手机号" />
							</view>
							<view class="input-container sms-container">
								<input v-model="smsCode" type="number" class="form-input sms-input" name="smsCode"
									placeholder="请输入短信验证码" />
								<button @click="sendSmsCode" :disabled="isSending" class="sms-btn">
									{{smsButtonText}}
								</button>
							</view>
						</view>

						<view class="submit-container">
							<button formType="submit" class="login-button">
								<view>{{login_text}}</view>
							</button>
						</view>

						<view class="agreement-container">

							<radio :checked="is_ok" @click="ok" />
							<text>登录即表示您同意</text><text class="gui-color-blue"
								@click="Policy('privacy')">《隐私政策》</text>及<text class="gui-color-blue"
								@click="Policy('user')">《用户协议》</text>

						</view>
					</form>

					<view class="oauth" >
						<!-- 第三方登录按钮 -->
						<view v-if="dd_login" >
							<image  style="width: 64rpx;height:64rpx;" src="@/static/login/dingding.png" @click="dingding_login"></image>
							<text>钉钉</text>
						</view>
					</view>

					<view class="footer-text" @click="to_dingding">
						<text class="gui-text gui-block">柳州博亚科技有限公司 提供技术支持</text>
						<text class="gui-text gui-block">柳钢域名备案号 桂ICP备17009352号</text>
						<text class="gui-text gui-block">桂公网安备4502020200044</text>
						<!-- <text class="gui-text gui-block">v.{{app_ver}}</text> -->
					</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>
<script>
	import graceChecker from "@/Grace6/js/checker.js";
	import request from "@/Grace6/js/request.js";
	const dd_login = uni.requireNativePlugin('WHY-Login')
	import sign from "@/Grace6/js/sign.js";
	import qs from 'qs'
	import string from '@/Grace6/js/string.js';
	import boya from "../../Grace6/js/boya";
	import config from "../../config";



	export default {
		components: {

		},
		data() {
			return {
				app_ver: null,
				token: 'token',
				save_password: false,
				is_ok: false,
				userName: '',
				password: '',
				showPassword: true,
				system: '',
				login_text: '立即登录',
				is_submit: false,
				push_id: null,
				os: 'andrios',
				oauth: '',
				wx_login: false,
				ios_login: false,
				dd_login:false ,
				h5n: 0,
				// 新增字段
				loginType: 'password', // 登录方式：password-账号密码，sms-短信验证
				phoneNumber: '', // 手机号
				smsCode: '', // 短信验证码
				isSending: false, // 是否正在发送验证码
				countdown: 60, // 验证码倒计时
				smsButtonText: '获取验证码', // 验证码按钮文本
				timer: null, // 定时器
				dd_num: 0
			}
		},
		beforeCreate() {

		},
		created() {
			let sys_info = uni.getSystemInfoSync()
			this.system = sys_info.osName;
			if (this.system.toLowerCase().indexOf("android"))
				console.log("system", this.system);
			let tts_token = uni.getStorageSync("ttsxAuthToken");
			let token = uni.getStorageSync("uuid")
			console.log("tts_token", tts_token);
			console.log("token", token);
			let self = this;
			console.log("sys_info", sys_info);
			this.app_ver = sys_info.appVersionCode ?? sys_info.appVersion;

			if (uni.getSystemInfoSync().platform === 'android' || uni.getSystemInfoSync().platform === 'ios') {
				plus.runtime.getProperty(plus.runtime.appid, (appInfo) => {
					self.app_ver = appInfo.version
				});
			} else {
				console.log('当前非App环境');
			}

			console.log()


		},
		onLoad(opt) {
			let self = this;
			console.log("login", opt);
			uni.getPushClientId({
				success(res) {
					console.log("push_id", res.cid);
					self.push_id = res.cid;
				}
			})
			if (opt.logout == 1) {
				uni.removeStorageSync("uuid");
				uni.removeStorageSync("member");
				uni.removeStorageSync("userInfo");
				uni.removeStorageSync("ttsxAuthToken");
			}

			this.$comm.get_appPages(function(res) {
				console.log("beforeCreate", res);

				// uni.showToast({
				// 	title:"更新完毕",
				// 	icon:"none"
				// })
			}, false, "all")

			uni.hideLoading();
			this.userName = uni.getStorageSync("userName");
			this.password = uni.getStorageSync("password");


			if (opt.logout != 1 && this.password) {
				this.save_password = true;
				this.is_ok = true;
				this.submit();
			}
			// #ifdef APP-PLUS
			uni.getProvider({
				service: "oauth",
				success(res) {
					console.log("getProvider", res);
					self.oauth = res.provider;
					res.providers.map((d) => {
						console.log("provider", d);
						if (d.id == "weixin" && d.isAppExist) {
							self.wx_login = true;
						}
						if (d.id = "apple" && d.isAppExist) {
							self.ios_login = true;
						}

					})

				}
			})

			this.os = uni.getSystemInfoSync().osName;
			console.log("os", this.os);

			// uni.getPushClientId({
			// 	success(res) {
			// 		console.log("push_id", res.cid);
			// 		self.push_id = res.cid;
			// 	}
			// })
			// #endif

			dd_login.isDDAppInstalled(isApp => {
				if (isApp) {
					self.dd_login = true;
				}
			})

		},
		methods: {
			// 切换登录方式
			switchLoginType(type) {
				this.loginType = type;
			},
			to_dingding() {
				this.dd_num++;
				if (this.dd_num > 5) {
					uni.redirectTo({
						url: "/pages/test/dingding"
					})
				}
			},
			dingding_login() {
				uni.redirectTo({
					url: "/pages/test/dingding"
				})
			},
			// 发送短信验证码
			sendSmsCode() {
				if (this.isSending) return;

				// 验证手机号
				if (!this.phoneNumber || !/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}

				this.isSending = true;
				this.countdown = 60;
				this.smsButtonText = `${this.countdown}秒后重发`;

				// 发送验证码请求
				this.$boya.NPost('/app/sms_code', {
					phone: this.phoneNumber,
					type: 'login'
				}, (res) => {
					uni.showToast({
						title: '验证码已发送',
						icon: 'success'
					});

					// 开始倒计时
					this.timer = setInterval(() => {
						this.countdown--;
						this.smsButtonText = `${this.countdown}秒后重发`;

						if (this.countdown <= 0) {
							clearInterval(this.timer);
							this.isSending = false;
							this.smsButtonText = '获取验证码';
						}
					}, 1000);
				}, (err) => {
					this.isSending = false;
					this.smsButtonText = '获取验证码';
					uni.showToast({
						title: err.msg || '发送失败，请重试',
						icon: 'none'
					});
				});
			},

			// 跳转到注册页面
			goToRegister() {
				uni.navigateTo({
					url: '/pages/login/register'
				});
			},

			click_ICP() {
				let url = 'https://beian.miit.gov.cn'
				window.location.href = url
			},
			device_login() {
				this.$boya.NPost("device_login", {
					dev_id: this.push_id
				}, function(res) {
					console.log("device_login", res);
				});
			},
			checkOA(oa) {
				for (let key in this.oauth) {
					if (this.oauth[key].id == oa) {
						if (this.oauth[key].isAppExist) {
							return true;
						} else {
							return false;
						}
					}
				}
				return false;
			},
			ioslogin() {
				if (this.is_ok == false) {
					uni.showToast({
						title: "请阅读并勾选页面协议",
						icon: "none"
					})
					return;
				}
				let self = this;
				console.log("ioslogin");
				uni.login({
					provider: 'apple',
					success: function(loginRes) {
						console.log("ios", loginRes);
						self.$comm.log("ios->login->ok=" + JSON.stringify(loginRes));
						// 登录成功
						uni.getUserInfo({
							provider: 'apple',
							success: function(info) {
								console.log("ios->userInfo", info.user);
								self.$comm.log("ios->login->userInfo=" + JSON.stringify(info));
								self.$boya.NPost("/app/openid_login", {
									openid: loginRes.authResult.openid,
									type: "ios"
								}, function(res) {
									console.log("ios->ok", res)
									self.login_ok(res);
								}, function(err) {
									console.log("ios-error", err);

									if (err.msg.code == 2) {
										uni.navigateTo({
											url: "/pages/login/wx_bind?type=ios&openid=" +
												loginRes.authResult.openid
										});
									}
									// uni.navigateTo({
									// 	url:"/pages/MY/log?log="+escape( JSON.stringify(err))
									// })

									//console.log("err",err);
								})
								// 获取用户信息成功, info.authResult中保存登录认证数据
							}
						})
					},
					fail: function(err) {
						console.log("ioslogin-error", err);
						self.$comm.log("ios->login->error=" + JSON.stringify(err));
						uni.navigateTo({
							url: "/pages/MY/log?log=" + escape(JSON.stringify(err))
						})
						// 登录授权失败  
						// err.code错误码参考`授权失败错误码(code)说明`
					}
				});
			},
			wxlogin() {
				if (this.is_ok == false) {
					uni.showToast({
						title: "请阅读并勾选页面协议",
						icon: "none"
					})
					return;
				}
				let self = this;
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(loginRes) {
						const {
							code
						} = loginRes
						console.log("wxlogin->login", loginRes);
						self.$boya.NGet("/openid/code", {
							code: loginRes.code,
							device: 'app'
						}, function(res) {
							console.log(res);
							let openid = res.data.openid;
							console.log("openid", openid);
							self.$boya.NPost("/app/openid_login", {
								openid: openid
							}, function(res) {
								console.log("ok", res)
								self.login_ok(res);
							}, function(err) {
								console.log("err", err);
								uni.navigateTo({
									url: "/pages/login/wx_bind?type=wx&openid=" +
										openid
								});

							})
						})

					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
					}
				})
			},
			forgetPwd: function() {
				uni.navigateTo({
					url: "/pages/login/forgetPassword"
				})
			},
			jf_login() {
				// this.$boya.login();
				console.log(this.userName, this.password)
			},
			submit(e) {
				if (this.is_submit) return;
				console.log(e)
				let self = this;

				// 判断登录方式
				if (this.loginType === 'password') {
					// 账号密码登录
					// 表单数据
					var formData = {
						username: this.userName,
						password: this.password
					}
					console.log("formData", formData);

					// 利用 graceUI 的表单验证工具进行验证
					//定义表单规则
					var rule = [{
							name: "username",
							checkType: "string",
							checkRule: "5,50",
							errorMsg: "登录账户输入有误"
						},
						{
							name: "password",
							checkType: "string",
							checkRule: "6,100",
							errorMsg: "登录密码至少6个字符"
						},
					];
					var checkRes = graceChecker.check(formData, rule);
					if (this.is_ok == false) {
						uni.showToast({
							title: "请阅读并勾选页面协议",
							icon: "none"
						})
					} else {
						if (checkRes) {
							let self = this;
							// 根据项目需要完成数据验证工作

							let data = {
								userName: formData.username,
								password: this.$lg.base64encode(formData.password)
								// password:"Q2RjMjI4ODEx"
							};
							//data["dev"]=1; //开放专用,跳过天拓的登录
							// #ifdef APP-PLUS
							data["devicesId"] = this.push_id;
							// #endif
							data["ttsxAuthSign"] = sign.sign(data).toString();
							console.log("login.data", data);

							let url = "https://app.lgwisdomunion/APP/app/login";

							// #ifdef H5
							console.log('执行了H5')
							url = "/test/APP/app/login";
							// #endif

							uni.setStorageSync("userName", this.userName);
							uni.showLoading({
								title: "登录中"
							});

							uni.setStorageSync("ld", {
								u: formData.username,
								p: formData.password
							});
							if (this.save_password) {
								uni.setStorageSync("password", formData.password);
							}
							this.login_text = "登录中.."
							this.is_submit = true;
							if (this.push_id) {
								data["push_id"] = this.push_id;
							}
							data["os"] = this.os;
							data["app_ver"] = this.app_ver;
							if (config.dev) {
								data["dev"] = 1
							}

							console.log('login_data：', data);

							this.$boya.NPost("/app/login", data, function(res) {
								console.log("登录成功-->res", res);
								if (typeof res.data == "string") {
									if (res.data == "new_user") {
										uni.showModal({
											title: "提示",
											content: "新用户完善您的基本资料!",
											showCancel: false,
											success(res) {
												if (res.confirm) {
													uni.removeStorageSync("ld");
													uni.removeStorageSync("password");
													uni.navigateTo({
														url: "/pages/login/info_edit?username=" +
															data["userName"]
													})
												}
											}
										})

										return;
									}
									if (res.data.indexOf("edit_pass") >= 0) {
										//要求修改密码
										let token = res.data;
										uni.showModal({
											title: "修改密码",
											content: res.msg,
											showCancel: false,
											confirmText: "修改密码",
											success(res) {
												if (res.confirm) {
													uni.removeStorageSync("ld");
													uni.removeStorageSync("password");
													uni.navigateTo({
														url: "/pages/login/edit_pass?username=" +
															data["userName"] + "&pass=" + data[
																"password"] + "&token=" + self.$lg
															.base64encode(token)
													})
												}
											}
										})
										return;
									}
								}
								

								self.login_ok(res);

							}, function(err) {
								self.is_submit = false;
								console.log("登录失败-->err", err);
								if (err) {

									uni.showToast({
										icon: "none",
										title: err.msg,
										duration: 3000
									});

								}
								self.login_text = "立即登录"
							}, {
								showError: false
							})

						} else {
							self.is_submit = false;
							self.login_text = "立即登录"
							uni.showToast({
								title: graceChecker.error,
								icon: "none"
							});
						}
					}
				} else if (this.loginType === 'sms') {
					// 短信验证码登录
					// 验证手机号和验证码
					if (!this.phoneNumber || !/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
						uni.showToast({
							title: '请输入正确的手机号',
							icon: 'none'
						});
						return;
					}

					if (!this.smsCode || this.smsCode.length !== 6) {
						uni.showToast({
							title: '请输入6位验证码',
							icon: 'none'
						});
						return;
					}

					if (this.is_ok == false) {
						uni.showToast({
							title: "请阅读并勾选页面协议",
							icon: "none"
						});
						return;
					}

					this.login_text = "登录中..";
					this.is_submit = true;

					// 发送短信验证码登录请求
					this.$boya.NPost("/app/sms_login", {
						phone: this.phoneNumber,
						code: this.smsCode,
						push_id: this.push_id,
						os: this.os
					}, (res) => {
						console.log("短信登录成功-->res", res);
						self.login_ok(res);
					}, (err) => {
						self.is_submit = false;
						console.log("短信登录失败-->err", err);
						if (err) {
							uni.showToast({
								icon: "none",
								title: err.msg || '登录失败'
							});
						}
						self.login_text = "立即登录";
					}, {
						showError: false
					});
				}
			},
			login_ok(res) {
				console.log("login_ok", res);
				uni.setStorageSync("ttsxAuthToken", res.data.ttsxAuthToken);
				uni.setStorageSync("userInfo", res.data.user);
				uni.setStorageSync("token", res.data.token);
				if (res.data.hasOwnProperty("Bearer")) {
					uni.setStorageSync("Bearer", res.data.Bearer);
				}
				console.log("uuid", res.data.uuid);
				uni.setStorageSync("member", res.data.member);
				uni.setStorageSync("platformMall", "c69a70c5-de6f-44fa-a333-88c5a5b3ff77");

				this.redirectToHome();

			},
			clearUname() {
				this.userName = ''
			},
			clearPassword() {
				this.password = ''
			},

			changePwdType() {
				this.showPassword = !this.showPassword
			},
			Policy(e) {
				uni.navigateTo({
					url: "/pages/login/agreement/agreement?type=" + e
				});
			},
			ok() {
				this.is_ok = !this.is_ok
				console.log(this.is_ok)
			},
			savePassword() {
				this.save_password = !this.save_password
				console.log(this.save_password)
			},
			open_h5() {
				this.h5n++;
				console.log(this.h5n);
				if (this.h5n > 5) {
					uni.showToast({
						title: "开启全H5模式"
					})

				}
				uni.reLaunch({
					url: "/pages/test/h5/h5"
				})
			},


			redirectToHome() {
				if (this.h5n == 0) {
					uni.reLaunch({
						url: "/pages/switchPages/main"
					});
				} else {
					uni.reLaunch({
						url: "/pages/test/h5/h5"
					})
				}
			}

		}
	}
</script>
<style scoped>
	/* 背景图片样式 */
	.login-container {
		background-image: url('@/static/login/lg_bg.jpg');
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		min-height: 100vh;
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-end;
		/* 改为底部对齐 */
	}

	/* 登录内容容器 */
	.login-content {
		width: 85%;
		max-width: 650rpx;
		padding: 40rpx 20rpx 80rpx;
		/* 增加底部padding */
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 50rpx;
		/* 距离底部的距离 */
	}

	/* Logo样式 */
	.logo-container {
		margin-bottom: 30rpx;
		text-align: center;
	}

	.logo-image {
		width: 300rpx;
		/* 稍微缩小logo */
		height: auto;
	}

	/* 登录方式切换 */
	.login-type-switch {
		display: flex;
		justify-content: space-around;
		width: 100%;
		margin-bottom: 40rpx;
	}

	.login-type-switch text {
		font-size: 32rpx;
		color: #fff;
		padding: 10rpx 20rpx;
		position: relative;
	}

	.active-tab {
		color: #F3C822 !important;
		font-weight: bold;
	}

	.active-tab::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #F3C822;
	}

	/* 表单样式 */
	.login-form {
		width: 100%;
	}

	.input-container {
		position: relative;
		margin-bottom: 30rpx;
	}

	.form-input {
		height: 90rpx;
		background-color: #FFFFFF;
		border-radius: 45rpx;
		padding: 0 80rpx 0 30rpx;
		width: 100%;
		box-sizing: border-box;
	}

	.input-icon {
		position: absolute;
		right: 30rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #999;
	}

	.form-options {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		font-size: 26rpx;
		color: #F8E010;
	}

	/* 短信验证码 */
	.sms-container {
		display: flex;
		align-items: center;
	}

	.sms-input {
		flex: 1;
	}

	.sms-btn {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 24rpx;
		background: #F3C822;
		color: #000;
		border-radius: 40rpx;
		margin-left: 20rpx;
		padding: 0;
	}

	/* 登录按钮 */
	.submit-container {
		margin: 40rpx 0 30rpx;
	}

	.login-button {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 45rpx;
		background: linear-gradient(to bottom, #EEE6B3, #F3C822);
		color: #333;
		font-size: 32rpx;
		font-weight: bold;

	}

	/* 协议 */
	.agreement-container {
		font-size: 26rpx;
		color: #F3C822;
		border: 1px solid #F3C822;
		padding: 15rpx;
		border-radius: 50rpx;
		text-align: center;
		margin-bottom: 30rpx;
	}

	/* 底部文字 */
	.footer-text {
		color: #FFFFFF;
		font-size: 24rpx;
		text-align: center;
		margin-top: 10rpx;
	}

	/* 第三方登录 */
	.oauth {
		display: flex;
		justify-content: center;
		gap: 40rpx;
		margin: 10rpx 0rpx;
	}
	.oauth view{
		display: flex;
		flex-direction:column;
		align-items: center;
		justify-content: center;
		color: white;
		gap:6rpx;
		font-size: 24rpx;
	}
</style>